#!/bin/bash

echo "🔧 修复构建错误 - 编译缺失的文件"

# 清理并重新构建
rm -rf bin .objs
mkdir -p bin .objs

# 编译设置
INCLUDES="-I../cbp2make/lib -I../cbp2make/lib/tinyxml -I../cbp2make/src -Ilib -Isrc"
CXXFLAGS="-std=c++11 -DAICODER_ENHANCED -m64"

echo "📝 编译所有必要文件..."

# 明确列出所有需要编译的文件
compile_file() {
    local file=$1
    local base=$(basename "$file" .cpp)
    echo "  编译: $base.cpp"
    g++ $INCLUDES $CXXFLAGS -c "$file" -o ".objs/$base.o" >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "    ✅ 成功"
        return 0
    else
        echo "    ❌ 失败"
        # 显示详细错误
        g++ $INCLUDES $CXXFLAGS -c "$file" -o ".objs/$base.o"
        return 1
    fi
}

echo "🔸 AI 文件:"
compile_file "src/aicoder_enhancements.cpp"

echo ""
echo "🔸 cbp2make 核心文件:"
CBP_FILES=(
    "../cbp2make/src/cbp2make.cpp"
    "../cbp2make/src/cbproject.cpp"
    "../cbp2make/src/cbworkspace.cpp"
    "../cbp2make/src/makefile.cpp"
    "../cbp2make/src/cbptarget.cpp"
    "../cbp2make/src/cbpunit.cpp"
    "../cbp2make/src/cbbuildcfg.cpp"
    "../cbp2make/src/cbbuildmgr.cpp"
    "../cbp2make/src/cbglobalvar.cpp"
    "../cbp2make/src/cbhelper.cpp"
    "../cbp2make/src/depsearch.cpp"
    "../cbp2make/src/platforms.cpp"
    "../cbp2make/src/toolchains.cpp"
    "../cbp2make/src/buildtools.cpp"
)

for file in "${CBP_FILES[@]}"; do
    compile_file "$file"
done

echo ""
echo "🔸 STL 工具库:"
STL_FILES=(
    "../cbp2make/lib/stlconfig.cpp"
    "../cbp2make/lib/stlconvert.cpp"
    "../cbp2make/lib/stlfutils.cpp"
    "../cbp2make/lib/stlgpm.cpp"
    "../cbp2make/lib/stlstrings.cpp"
    "../cbp2make/lib/stlvariables.cpp"
    "../cbp2make/lib/stringhash.cpp"  # 这个包含 sdbm_hash 函数！
)

for file in "${STL_FILES[@]}"; do
    compile_file "$file"
done

echo ""
echo "🔸 TinyXML 核心库:"
TINYXML_FILES=(
    "../cbp2make/lib/tinyxml/tinystr.cpp"
    "../cbp2make/lib/tinyxml/tinyxml.cpp"
    "../cbp2make/lib/tinyxml/tinyxmlerror.cpp"
    "../cbp2make/lib/tinyxml/tinyxmlparser.cpp"
)

for file in "${TINYXML_FILES[@]}"; do
    compile_file "$file"
done

# 链接
echo ""
echo "🔗 链接可执行文件..."
g++ -m64 .objs/*.o -o bin/cbp2make_ai

if [ -f "bin/cbp2make_ai" ]; then
    echo ""
    echo "🎉 修复构建成功!"
    echo "📊 统计:"
    echo "   - 对象文件: $(find .objs -name "*.o" | wc -l) 个"
    echo "   - 可执行文件: bin/cbp2make_ai"
    echo ""
    echo "🧪 测试AI功能:"
    ./bin/cbp2make_ai --ai-help
else
    echo "❌ 构建失败"
    g++ -m64 .objs/*.o -o bin/cbp2make_ai 2>&1 | head -10
fi
